package org.example.service.impl;

import org.example.mapper.FruitInboundMapper;
import org.example.mapper.FruitMapper;
import org.example.mapper.InventoryMapper;
import org.example.MyExecption.BusinessException;
import org.example.domain.Fruit;
import org.example.domain.FruitInbound;
import org.example.domain.FruitInventory;
import org.example.myEnum.ErrorCode;
import org.example.service.FruitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 水果服务实现类
 */
@Service
public class FruitServiceImpl implements FruitService {

    private static final Logger logger = LoggerFactory.getLogger(FruitServiceImpl.class);

    @Autowired
    private FruitMapper fruitMapper;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url}")
    private String uploadUrl;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private FruitInboundMapper fruitInboundMapper;


    @Override
    public List<Fruit> getAllFruits() {
        return fruitMapper.findAll();
    }

    @Override
    public Fruit getFruitById(Long id) {
        return fruitMapper.findById(id);
    }

    @Override
    @Transactional
    public Fruit addFruit(Fruit fruit, MultipartFile imageFile) {
       try {
           // 处理图片上传
           if (imageFile != null && !imageFile.isEmpty()) {
               String imagePath = uploadImage(imageFile);
               fruit.setImage(imagePath);
           }
       }catch (Exception e){
           logger.warn("图片尺寸过大");
           throw new BusinessException(ErrorCode.TO_LARGER_PICTURE);
       }

        // 保存水果信息
        fruitMapper.insert(fruit);
        return fruit;
    }

    @Override
    @Transactional
    public Fruit updateFruit(Fruit fruit, MultipartFile imageFile) {
        // 如果上传了新图片，则更新图片
        if (imageFile != null && !imageFile.isEmpty()) {
            // 获取原水果信息
            Fruit oldFruit = fruitMapper.findById(fruit.getId());
            if (oldFruit != null && oldFruit.getImage() != null) {
                // 删除旧图片
                deleteImage(oldFruit.getImage());
            }
            
            // 上传新图片
            String imagePath = uploadImage(imageFile);
            fruit.setImage(imagePath);
        }

        // 更新水果信息
        fruitMapper.update(fruit);
        return fruit;
    }

    @Override
    @Transactional
    public void deleteFruit(Long id) {
        // 获取水果信息
        Fruit fruit = fruitMapper.findById(id);
        //根据品类信息查看是否还有库存
        if (fruit != null && fruit.getImage() != null) {
            // 删除图片
            deleteImage(fruit.getImage());
        }
        
        // 删除水果信息
        fruitMapper.deleteById(id);
    }
    /***
     * 获取所有水果名称列表
     * @return
     */
    @Override
    public List<Fruit> list() {
        return fruitMapper.list();
    }
    /**
     * 查看是否有编辑按钮所有权限
     * @return
     */
    @Override
    public Integer editPermission(Integer id) {
        //根据id查询水果信息
        Fruit fruit = fruitMapper.selectById(id);
        //根据名称查询是否还有剩余库存
        HashMap<String, Object> selectMap = new HashMap<>();
        selectMap.put("fruit_name",fruit.getName());
        List<FruitInventory> inventoryList = inventoryMapper.selectByMap(selectMap);
        if (inventoryList.size()!=0){
            return 1;
        }
        //根据名称查询入库单中是否有未审核的入库单
        selectMap.put("status","0");
        List<FruitInbound> fruitInbounds = fruitInboundMapper.selectByMap(selectMap);
        if (fruitInbounds.size()!=0){
            return 1;
        }
        return 0;
    }
    /**
     * 上架,下架水果
     * @return
     */
    @Override
    public Integer status(Integer id, String type) {
        return fruitMapper.changeStatusById(id,type);
    }

    /**
     * 上传图片
     * @param file 图片文件
     * @return 图片路径
     */
    private String uploadImage(MultipartFile file) {
        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        File destFile = new File(uploadPath + File.separator + filename);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException("图片上传失败", e);
        }
        
        // 返回可访问的URL
        return uploadUrl + "/" + filename;
    }

    /**
     * 删除图片
     * @param imagePath 图片路径
     */
    private void deleteImage(String imagePath) {
        if (imagePath != null && imagePath.startsWith(uploadUrl)) {
            String filename = imagePath.substring(imagePath.lastIndexOf("/") + 1);
            File file = new File(uploadPath + File.separator + filename);
            if (file.exists()) {
                file.delete();
            }
        }
    }
} 